package com.example.enginsdk;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputConnection;

import com.csizg.imemodule.activity.InputSettingsActivity;
import com.csizg.imemodule.adapter.RecyclerCandidatesTabItemAdapter;
import com.csizg.imemodule.adapter.RecyclerSkbSettingsAdapter;
import com.csizg.imemodule.application.LauncherManager;
import com.csizg.imemodule.constant.CustomConstant;
import com.csizg.imemodule.listener.OnDeleteClickListener;
import com.csizg.imemodule.listener.OnRecyclerItemClickListener;
import com.csizg.imemodule.manager.LocalRepository;
import com.csizg.imemodule.manager.SkbContainer;
import com.csizg.imemodule.manager.SkbInitBuilderManager;
import com.csizg.imemodule.service.PinyinIME;
import com.csizg.imemodule.utils.LogUtil;
import com.csizg.rime.RimeConfig;

import java.util.ArrayList;


/**
 * @author leo
 * @date 2020/5/18
 * @description： imeSDK控制类
 */
public class ImeSdkManager implements OnRecyclerItemClickListener {
    private static final String TAG = ImeSdkManager.class.getSimpleName();

    private static ImeSdkManager mSKDManager;

    private Context mContext;

    private SkbInitBuilderManager mInitBuilderManager;

    public static final String IS_IN_APP = "is_inAPP";

    public static ImeSdkManager getSKDManager() {
        if (null == mSKDManager) {
            mSKDManager = new ImeSdkManager();
        }
        return mSKDManager;
    }

    private void initSkb() {
        mInitBuilderManager = SkbInitBuilderManager.getInstance();

        mInitBuilderManager.setIsUploadUserDic(true)
                //整拼键盘
                .setIsZhengpin(false)
                //注音键盘
                .setIsZhuyin(false)
                //笔画键盘
                .setIsBihua(false)
                //大九键
                .setIsOpenBigNineKey(true)
                // 手写键盘
                .setIsOPenSX(true)
                // 是否开启候选词上的加密按钮
                .setIsOpenCandidatesEncryBtn(true)
                //候选词颜色
                .setIsOpenALB(true)
                .setActColor("#EB5E5E")
                //长按弹窗文字背景颜色
                .setballoonSelectorRecource(android.R.color.holo_blue_light)
                //设置键盘切换时的文字选中颜色
                .setKeyItemTextColor("#EB5E5E")
                //设置Emoji表情标题文字选中颜色
                .setEmojiTitleTypeTextColor("#EB5E5E")
                //键盘最下面添加标语
                .setSkbTips("null")
                //动态添加的功能栏自定义view的list
                .addTabItemList(AddSkbTabUtil.getAddSkbTabUtil(mContext).getSkbTabLoginList())
                //动态添加的功能栏自定义view的list
                .addTabItemListUnLogin(AddSkbTabUtil.getAddSkbTabUtil(mContext).getSkbTabList())
                //点击应用图标后功能栏
                .addFunItemList(new ArrayList<>())
                //点击应用图标后功能栏
                .addKeyboardItemList(AddSkbTabUtil.getAddSkbTabUtil(mContext).getListKeyboard())
                .setItemOnclick(this)
                .setOnDeleteClickListener(new OnDeleteClickListener() {
                    @Override
                    public boolean onDeleteClick(InputConnection connection) {
                        return deleteZeroWidthCharIfNeeded(connection);
                    }
                })
                // 添加加密联系人
//            .addSdkPinyinTitleView(AddSkbTabUtil.getAddSkbTabUtil(mContext).getContactsView())
                // 添加拼音栏的牛头
//            .addSdkPinyinTitleIcon(R.mipmap.icon_keyboard_lock)
                .setOnIconClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // 牛头点击
                    }
                })
                // 开启候选词栏中的加密按钮
                .setIsOpenCandidatesEncryBtn(true)
                // 候选词栏显示加密按钮时的加密按键点击事件
                .setOnEncryClickListener(text -> {
                    //加密键回调,特殊页面不需要处理加密逻辑
//                Activity lastShowingActivity = ActivityManager.getActivityManager().getLastShowingActivity();
//                if (lastShowingActivity instanceof ChatGroupConversationActivity ||
//                    lastShowingActivity instanceof ChatConversationActivity ||
//                    lastShowingActivity instanceof SecretChatActivity || lastShowingActivity instanceof SelectFriendActivity ||
//                    lastShowingActivity instanceof MultipleSendActivity ||
//                    lastShowingActivity instanceof GroupNotificationEditActivity) {
//                } else {
//                    if (ActivityManager.getActivityManager().getLastShowingActivity() == null) {
//                        if (!FloatWindowManager.checkPermission(TheApplication.getAppContext())) {
//                            TheApplication.getAppContext()
//                                .startActivity(new Intent(TheApplication.getAppContext(), ShowDialogActivity.class));
//                            return;
//                        }
//                    }
//                    ImeSDKEncryptManager.getEncryptManager(mContext).onClickEncrypt(text);
//                }
                });
    }

    /**
     * 初始化sdk控制类
     */
    public ImeSdkManager initData(Context context) {
        synchronized (ImeSdkManager.class) {
            this.mContext = context;
            // 词库初始化等操作在 LauncherManager 中
            RimeConfig.init(context);
            try {
                LauncherManager.getInstance().initData(context);
            } catch (Exception e) {
                e.printStackTrace();
                LogUtil.d("词典初始化异常", "", e.getMessage());
            }
            LocalRepository.getInstance().initEventBus(LauncherModel.getInstance().getGlobalEventBus());
            //判断用户登录状态，退出应用后获取仍为true
            initSkb();
            return mSKDManager;
        }
    }


    /**
     * 在文字删除操作时，删除多余的零宽字符
     */
    private boolean deleteZeroWidthCharIfNeeded(InputConnection ic) {
        if (ic == null) {
            return false;
        }
        CharSequence textBeforeCursor = ic.getTextBeforeCursor(100000, 0);
        if (textBeforeCursor == null) {
            textBeforeCursor = "";
        }
        CharSequence textAfterCursor = ic.getTextAfterCursor(100000, 0);
        if (textAfterCursor == null) {
            textAfterCursor = "";
        }

        String text = "" + textBeforeCursor + textAfterCursor;
        if (TextUtils.isEmpty(text)) {
            return false;
        }

        int start = textBeforeCursor.length();
        if (start != 0) {
            start -= 1;
        }

//        Pair<Integer, Integer> index = IndexUtils.searchZeroWidthString(text, start);
//        if (start != 0 && IndexUtils.isZeroWidthChar(textBeforeCursor.charAt(textBeforeCursor.length() - 1))) {
//            index = new Pair<>(index.first - 1, index.second);
//        }
//        if (index.first >= 0) {
//            ic.deleteSurroundingText(start - index.first + 1, index.second - start);
//            return true;
//        }
        return false;
    }

    @Override
    public void onItemClick(RecyclerView.Adapter adapter, View view, int i) {
        LogUtil.d(TAG, "onItemClick", "adapter: " + adapter + " ,i= " + i);
        SkbContainer skbContainer = PinyinIME.getPinyinIME().getSkbContainer();
        if (adapter instanceof RecyclerSkbSettingsAdapter) {
            skbContainer = PinyinIME.getPinyinIME().getSkbContainer();
            skbContainer.changeViewOnClickFun();
            skbContainer.showSkbTypeView(CustomConstant.SYMBOLS_TYPR_SELECT_MODE);
        }

        if (adapter instanceof RecyclerCandidatesTabItemAdapter) {
            switch (i) {
                case 0:
                    skbContainer = PinyinIME.getPinyinIME().getSkbContainer();
                    if (skbContainer.getCurrentType() == CustomConstant.SYMBOLS_TYPR_SELECT_MODE) {
                        skbContainer.showSkbTypeView(CustomConstant.SKB_TYPR_KEYBOARD_MODE);
                    } else {
                        skbContainer.showSkbTypeView(CustomConstant.SYMBOLS_TYPR_SELECT_MODE);
                    }
                    break;
                case 1:
                    Intent intent = new Intent();
                    intent.putExtra(IS_IN_APP, false);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setClass(mContext, InputSettingsActivity.class);
                    mContext.startActivity(intent);
                    break;
            }

        }
    }
}
